from datetime import datetime

from greatwall.models import Wall
from greatwall.models import Stage
from greatwall.src import stage_ctrl

class WallOperations(object):
    
    def __init__(self):
        self.stage_ops = stage_ctrl.StageOperations()

    def create_wall(self, title='', owner='', descr=''):        
        wall = Wall()
        wall.title = title
        wall.owner = owner
        wall.date_created = datetime.today()
        wall.description = descr
        wall.save()        
        self.stage_ops.create_dummy_stages(wall=wall)
        return wall

    def get_all_walls(self):
        all_existing_walls = Wall.objects.order_by('date_created')
        return all_existing_walls

    def get_wall_by_id(self, wall_id):
        wall = Wall.objects.get(id=wall_id)
        return wall

    def get_all_active_walls(self):
        active_existing_walls = Wall.objects.filter(status='I').\
            order_by('date_created')
        return active_existing_walls

    def get_all_trash_walls(self):
        active_existing_walls = Wall.objects.filter(status='T').\
            order_by('date_created')
        return active_existing_walls

    def get_all_archived_walls(self):
        active_existing_walls = Wall.objects.filter(status='A').\
            order_by('date_created')
        return active_existing_walls

    def get_wall_contents(self, wall_id):
        wall_contents = []
        wall = self.get_wall_by_id(wall_id=wall_id)
        stages = wall.get_active_stages()
        for each_stage in stages:
            cards = each_stage.get_active_cards()
            wall_contents = wall_contents + [(each_stage, cards)]
        return wall_contents

    def get_starting_stage(self, wall_id):
        wall = self.get_wall_by_id(wall_id=wall_id)
        stages = wall.get_active_stages()
        return stages[0] 

    def save_stages(self, wall_id, stage_list):
        wall = self.get_wall_by_id(wall_id=wall_id)
        stge_list = [stage for stage in stage_list if stage.strip()]
        for stage_order in range(1, len(stge_list) + 1):
            stage_title = stge_list[stage_order - 1]
            stage_obj = self.stage_ops.get_stage_by_order_no(wall, stage_order)
            if stage_obj:
                stage_obj.title = stage_title
                stage_obj.save()
            else:
                stage = self.stage_ops.create_stage(wall=wall, title=stage_title,
                                                    order_no=stage_order, desc='')
